<!DOCTYPE html>
<html lang="en" xmlns="">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>

  <div style="margin: 1rem; width: 50rem; height: 30rem; border: 1px solid red">
    <svg id='svg' style="width: 100%; height: 100%; z-index:-1;position: fixed; ">

      <!--
        points:属性里定义了各个点的坐标，x和y坐标之间用逗号分别，多个坐标之间用空格分割
        fill：填充颜色(画折线一般把属性设置为none)
        stroke：边框颜色
        stroke-width：边框宽带
        ill-opacity：透明度
        stroke-opacity：边框的透明度
      -->
      <polyline id='polyline' points="" style="fill:white;stroke:#68f;stroke-width:2" ></polyline>
    </svg>
    <div id="title" style="margin: 1rem 0 0 10rem; width: 10rem; height: 5rem; border: 1px solid green;">

    </div>
    <div id="left" style="margin: 5rem 0 0 1rem; width: 5rem; height: 5rem; border: 1px solid blue;">

    </div>
  </div>

  <script>

    const debug = console.debug;

    /**
     * top 是上面的那个 div 的id
     * bottom 是下面的那个 div 的id
     */
    function drawLine(topId, bottomId, polylineId) {

      debug(`topId= ${topId}, bottomId= ${bottomId}, polylineId=${polylineId}`);

      if(!topId || !bottomId || !polylineId) {
        debug(`id 为空`);
        return;
      }

      const eleTop = document.getElementById(topId);
      if(!eleTop) {
        debug(`id=${topId} 标签不存在`);
        return;
      }
      const eleTopRect = eleTop.getBoundingClientRect();

      const eleBottom = document.getElementById(bottomId);
      if(!eleBottom) {
        debug(`id=${bottomId} 标签不存在`);
        return;
      }
      const eleBottomRect = eleBottom.getBoundingClientRect();

      const polyline = document.getElementById(polylineId);
      if(!polyline) {
        debug(`id=${polylineId} 标签不存在`);
        return;
      }

      const svg = polyline.parentNode;
      const scgRect = svg.getBoundingClientRect();

      const topX = eleTopRect.left - scgRect.left;
      const topY = eleTopRect.top - scgRect.top + eleTopRect.height / 2;

      const bottomX = eleBottomRect.left - scgRect.left + eleBottomRect.width / 2;
      const bottomY = eleBottomRect.top - scgRect.top;

      const pointStr = `${topX},${topY} ${bottomX},${topY} ${bottomX},${bottomY}`;
      polyline.setAttribute('points', pointStr);
    }

    drawLine('title', 'left', 'polyline');

    // const polyline = document.createElement('polyline');

    // let pointStr = `${topX},${topY} ${leftX},${topY} ${leftX},${leftY}`;
    // polyline.setAttribute('points', pointStr);
    // polyline.setAttribute('style', 'fill:white;stroke:#68f;stroke-width:2');

    // const svg = document.getElementById('svg');
    // svg.appendChild(polyline);
  </script>
</body>

</html>
